<?php
// 应用公共文件

use app\common\service\AuthService;
use app\common\service\lib\sms\SmsFactory;
use app\common\service\lib\sms\SmsTreasure;
use think\facade\Cache;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        return $check;
    }

}

if (!function_exists('checkMobile')) {

    /**
     * 手机号正则验证
     * @param $str
     * @return bool
     */
    function checkMobile($str)
    {
        $pattern = "/^1[3|4|5|7|8|9]\d{9}$/";
        if (preg_match($pattern, $str)) {
            return true;
        }
        return false;
    }
}


if (!function_exists('verifyCode')) {

    /**
     * 生成4位随机数   短信验证码
     * @return int
     */
    function verifyCode()
    {
        $code = mt_rand(1000,9999);
        return $code;
    }
}

if (!function_exists('getTree')) {

    /**
     * 层级递归
     * @param array $data
     * @param int $pid
     * @param string $html
     * @param int $level
     * @return array
     */
    function getTree(array $data, int $pid = 0, string $html = '|---|', int $level = 0) {
        static $arr = [];
        foreach ($data as $val) {
            if ($pid == $val['pid']) {
                // 重复一个字符多少次
                $val['cate_name'] = str_repeat($html, $level * 1) . $val['cate_name'];
                // 每次循环重复次数加一
                $val['level'] = $level + 1;
                $arr[] = $val;
                // 再次调用
                getTree($data, $val['id'], $html, $val['level']);
            }
        }
        // 返回参数
        return $arr;
    }
}


if (!function_exists('getSon')) {
    /**
     * 层级递归
     * @param array $data
     * @param int $pid
     * @param string $html
     * @param int $level
     * @return array
     */
    function getSon(array $data, int $pid = 0) {
        $arr = [];
        foreach ($data as $value){
            if ($value['pid'] == $pid){
                $value['son'] = getSon($data,$value['id']);
                $arr [] = $value;
            }
        }
        return $arr;
    }
}

if (!function_exists('randNumber')) {

    /**
     * 产生随机数
     * @return string
     */
    function randNumber()
    {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ1234567890';

        $len = strlen($str);
        //生成6位随机数
        for ($i = 0; $i < 6; $i++) {
            $str .= substr($str,mt_rand(0,$len-1),1);
        }

        return $str;
    }
}


if (!function_exists('requestGet')) {

    /**
     * curl get请求
     * @return string
     */
    function requestGet($url)
    {
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        curl_exec($ch);
        curl_close($ch);
    }
}

if (!function_exists('aliyunRequest')) {

    /**
     * aliyun curl请求
     * @return string
     */
    function aliyunRequest($url,$method,$headers,$host)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
    }
}

if (!function_exists('')) {
    /**
     * Author:Zhongyuan Lu
     * 判断文件是否是图片
     * @param $img
     * @return false|int
     */
    function isImage($img)
    {
        return preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $img);
    }
}

if (!function_exists('semVerification')) {

    /**
     * curl get请求
     * @return string
     */
    function semVerification($params)
    {
        $code = Cache::store('redis')->get($params['phone'] . 'code');
        if ($params['code'] !== $code) {
            return ['data'=>[], 'code'=>200, 'message'=>'验证成功'];
        }
        return ['data'=>[], 'code'=>400, 'message'=>'验证码错误'];
    }
}


if (!function_exists('encrypt')) {
    /**
     * Author:Zhongyuan Lu
     * 加密算法
     * @param $id
     * @return false|string
     */
    function encrypt($id)
    {
        //加盐
        $salt = config('setting.salt');
        $method = 'AES-128-ECB';
        $data = config('setting.saltRand').openssl_encrypt($id, $method, $salt,0);
        return openssl_encrypt($data, $method, $salt,0);
    }
}

if (!function_exists('decrypt')) {
    /**
     * Author:Zhongyuan Lu
     * 解密算法
     * @param $data
     * @return false|string
     */
    function decrypt($data)
    {
        //加盐
        $salt = config('setting.salt');
        $method = 'AES-128-ECB';
        $data = openssl_decrypt($data, $method, $salt,0);
        $data = str_replace(config('setting.saltRand'),'',$data);
        return openssl_decrypt($data, $method, $salt,0);
    }
}


if (!function_exists('three')) {
    function three($data)
    {
        $res = [];
        $arr = [];
        foreach ($data as $value) {
            $arr['value'] = $value['nid'];
            $arr['label'] = $value['city_name'];
            foreach ($value['son'] as $key=>$v) {
                $arr['children'][$key]['value'] = $v['nid'];
                $arr['children'][$key]['label'] = $v['city_name'];
                foreach ($v['son'] as $k=>$re) {
                    $arr['children'][$key]['children'][$k]['value'] = $re['nid'];
                    $arr['children'][$key]['children'][$k]['label'] = $re['city_name'];
                }
            }
            $res[] = $arr;
        }
        return $res;
    }
}

if (!function_exists('timeToDate')) {
    /**
     * Author:Zhongyuan Lu
     * 时间戳转为datetime-local可以展示的时间
     * @param $time
     * @return string
     */
    function timeToDate($time)
    {
        return date('Y-m-d',$time).'T'.date('H:i');
    }
}

if(!function_exists('create_unique')) {
    /**
     * Author:Zhongyuan Lu
     * 生成唯一邀请码
     * @param $len
     * @return false|string
     */
    function create_unique($len = 13) {
        $data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'] .time() . rand();
        return substr(sha1($data),0,$len);
        //return md5(time().$data);
    }
}
